package servlet;

import model.Order;
import util.JDBCUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ProcessOrderServlet.do")
public class ProcessOrderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取订单ID，这里假设订单ID在请求参数中传递过来
        String orderId = request.getParameter("order_id");

        // 假设这里需要更新订单状态为 processing
        boolean updateSuccess = updateOrderStatus(orderId);
        response.sendRedirect("register/checkout.jsp");
        if (updateSuccess) {
            out.println("<html><body>");
            out.println("<h2>订单支付成功！</h2>");
            out.println("<p>订单号：" + orderId + "</p>");
            out.println("<p>状态更新为：processing</p>");
            out.println("</body></html>");

        } else {
            out.println("<html><body>");
            out.println("<h2>订单支付处理失败，请重试！</h2>");
            out.println("</body></html>");
        }
    }

    // 模拟更新订单状态的方法
    private boolean updateOrderStatus(String orderId) {
        JDBCUtil jdbcUtil = new JDBCUtil();
        Order order=new Order();
        String sql = "UPDATE `order` SET order_status = processing WHERE order_id = ?";
        boolean result =false;
        try {
            result = jdbcUtil.paramsUpdate(sql,orderId);
        } finally {
            jdbcUtil.closeConnection();
        }
        return result;

    }
    public boolean updateOrder(Order order) {
        JDBCUtil jdbcUtil = new JDBCUtil();
        String sql = "UPDATE `order` SET recipient_name = ?, recipient_address = ?, recipient_phone = ?, notes = ?, order_status = ?, order_total = ? WHERE order_id = ?";
        boolean result =false;
        try {
            result = jdbcUtil.paramsUpdate(sql, order.getRecipient_name(), order.getRecipient_address(), order.getRecipient_phone(), order.getNotes(), order.getOrder_status(), order.getOrder_total(), order.getOrder_id());
        } finally {
            jdbcUtil.closeConnection();
        }
        return result;
    }

}
